package com.crm.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.crm.entity.Roles;
import com.crm.entity.User;
import com.crm.service.MailService;
import com.crm.service.RolesService;
import com.crm.service.UserService;
import com.crm.utils.AliyunMessageUtil;
import com.crm.utils.ResponeMessageUtil;
import com.crm.utils.TokenUtil;
import com.crm.vo.UserVo;
import com.fasterxml.jackson.core.JsonProcessingException;

@RestController
public class LoginController {
	
	@Autowired
	private MailService mailService;
	@Autowired
	private UserService userService;
	@Autowired
	private RolesService rolesService;
	
	HashMap<String, String> map =  new HashMap<>();//保存验证码和手机号
	
	@RequestMapping("/login")
	public Object login(String loginName,String password,String code,String phoneNumber) {
		Map<String, Object> hashMap = new HashMap<>();
		User user = null;
		if (code != null && code !="") {//手机号登录
			//验证
			if (map.get(phoneNumber).equals(code)) {
				hashMap.put("code", 0);
				hashMap.put("message", "验证码输入不正确");
				hashMap.put("data", user);
				//return ResponeMessageUtil.ok("验证码输入不正确", user);
				return hashMap;
			}
			
			//通过手机号查询
			 user = userService.selectByProtectMTel(phoneNumber);
		}else {//用户密码登录
			 user = userService.selectByNameAndPwd(loginName, password);
		}
		
		
		if (user == null) {
			hashMap.put("code", 0);
			hashMap.put("message", "用户名或密码输入不正确");
			hashMap.put("data", user);
			return hashMap;
			//return ResponeMessageUtil.ok("用户名密码输入不正确", user);
		} else {
			if (user.getIsLockout().equals("是")) {
				hashMap.put("code", 0);
				hashMap.put("message", "用户名已锁定，请联系管理员解锁");
				hashMap.put("data", null);
				return hashMap;
				//return ResponeMessageUtil.ok("用户名已锁定，请联系管理员解锁", user);
			} else {
				String token = "";
				try {
					token = TokenUtil.sign(user, 60*60*1000);
				} catch (UnsupportedEncodingException | JsonProcessingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return null;
				}
				//把token和用户信息返回给页面
				
				//查询用户的角色
				List<Roles> roles = rolesService.getRolesByUid(user.getId());
				user.setRoles(roles);
				String rids= "";
				for (int i=0;i<roles.size();i++) {
					if (i==roles.size()-1) {
						rids+=roles.get(i).getId();
					}else {
						rids+=roles.get(i).getId()+",";
					}
				}
				user.setRolesIds(rids);
				//返回结果
				Map<String, Object> map = new HashMap<>();
				map.put("code", "0");
				map.put("msg", "success");
				map.put("count", 0);
				map.put("data", user);
				map.put("token", token);
				return map;
			} 
		}
	}
	/**
	 * http://localhost:8080/springboot/sendEmail?protectEMail=自己的邮箱地址
	 * 获取验证码
	 * @param protectEMail
	 * @param httpSession
	 * @return
	 */
	 @PostMapping("/sendEmail")
	 @ResponseBody
	 public boolean sendEmail(String protectEMail, HttpSession httpSession){
	  return  mailService.sendMimeMail(protectEMail, httpSession)? true:false;
	 }
	 /**
	  * http://localhost:8080/springboot/regist?loginName=用户名称&password=密码&protectEMail=自己的邮箱地址&code=717786&token=
	  * 通过接收的邮箱验证码进行注册
	  * @param userVo
	  * @param session
	  * @return
	  */
	 @RequestMapping("/regist")
	 @ResponseBody
	 public boolean regist(UserVo userVo, HttpSession session){
	  return mailService.registered(userVo, session)? true:false;
	 }
	 
	 /**
	  * http://localhost:8080/springboot/loginMail?password=密码&protectEMail=自己的邮箱地址&token=
	  * 通过邮箱登录
	  * @param email
	  * @param password
	  * @return
	  */
	 @PostMapping("/loginMail")
	 @ResponseBody
	 public boolean loginMail(String protectEMail, String password){
	  return  mailService.loginIn(protectEMail,password)? true:false;
	 }
	 
	 
	 @PostMapping("/sendMobileCode")
	 
	 public Map<String, Object> sendMobileCode(String phoneNumber) throws ClientException {
		 String randomNum = getSixNum();
	        String jsonContent = "{\"code\":\"" + randomNum + "\"}";
	        Map<String, String> paramMap = new HashMap<>();
	        paramMap.put("phoneNumber", phoneNumber);
	        paramMap.put("jsonContent", jsonContent);
	        SendSmsResponse sendSmsResponse = AliyunMessageUtil.sendSms(paramMap);
	        if(!(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK"))) {
	            if(sendSmsResponse.getCode() == null) {
	                //这里可以抛出自定义异常
	            	Map<String, Object> map = new HashMap<>();
	            	map.put("code", "error");
	                return map;
	            }
	            if(!sendSmsResponse.getCode().equals("OK")) {
	                //这里可以抛出自定义异常
	            	//返回结果
	            	Map<String, Object> map = new HashMap<>();
	            	map.put("code", "error");
	                return map;
	            }
	        }
	        //把验证码保存到map
	        map.put(phoneNumber, randomNum);
	        
	        
	        //手机号验证码发送成功
	        Map<String, Object> map = new HashMap<>();
        	map.put("code", randomNum);
	        return map;
	}
	 
	 
	 public static String getSixNum() {
			String str = "0123456789";
			StringBuilder sb = new StringBuilder(4);
			for (int i = 0; i < 6; i++) {
				char ch = str.charAt(new Random().nextInt(str.length()));
				sb.append(ch);
			}
			return sb.toString();
		}

}
